﻿using AutoMapper;
using D.B.Data.API.Applications.Command.LeaveCommand;
using D.B.Data.Domain;
using D.B.Data.Domain.DTO.Output;
using D.B.Data.Domain.Enums;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;

namespace D.B.Data.API.Applications.CommandHandler.LeaveCommandHandler
{
    public class QueryLeaveCommandHandler : IRequestHandler<QueryLeaveCommand, APIPaging<QueryLeaveDTO>>
    {
        private readonly IBaseRepository<WorkflowModel> baseRepository;
        private readonly IBaseRepository<DeptModel> deptRepository;
        private readonly IMapper mapper;

        public QueryLeaveCommandHandler(IBaseRepository<WorkflowModel> baseRepository, IBaseRepository<DeptModel> deptRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.deptRepository = deptRepository;
            this.mapper = mapper;
        }

        public Task<APIPaging<QueryLeaveDTO>> Handle(QueryLeaveCommand request, CancellationToken cancellationToken)
        {
            var res = baseRepository.GetAll().Where(s => !s.IsDel);

            //查询 id 是否是部门领导 
            var isBoosId = deptRepository.GetAll().Where(s => s.BoosId.Equals(request.UserId)).Select(s => s.Id).ToList();

            //部门领导
            if(isBoosId.Any())
                res = res.Where(s => isBoosId.Contains(s.DeptId));
            else
                res = res.Where(s => s.UserId.Equals(request.UserId));



            if(!string.IsNullOrEmpty(request.UserName))
                res = res.Where(s => s.UserName.Contains(request.UserName));
           
            if(request.state!=null)
                res = res.Where(s => s.State == request.state);

            if (!string.IsNullOrEmpty(request.BeginTime))
                res = res.Where(s => s.LeaveTIme>=Convert.ToDateTime(request.BeginTime));

            if (!string.IsNullOrEmpty(request.EndTime))
                res = res.Where(s => s.ReportTIme < Convert.ToDateTime(request.EndTime).AddDays(1));

            var Count= res.Count();

            res = res.OrderByDescending(s => s.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);



            var model = mapper.Map<List<QueryLeaveDTO>>(res);
            foreach(var item in model)
            {
                item.DeptName = deptRepository.GetAll().FirstOrDefault(s => s.Id == request.UserId).DeptName;

            }


            APIPaging<QueryLeaveDTO> aPIPaging = new APIPaging<QueryLeaveDTO>()
            {
                Code=EnumCode.Ok,
                 Count=Count,
                  Msg="显示成功",
                   PageData=model
            };

            return Task.FromResult(aPIPaging);


        }
    }
}
